package com.qyer.commons.utils;/**
 * User: Z J Wu Date: 2016/01/06 Time: 17:23 Package: com.qyer.search.utils
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;

public class JsonOperator {

  private static class InnerHolder {

    private static final JsonOperator INSTANCE = new JsonOperator();
  }

  private JsonOperator() {
    objectMapper = new ObjectMapper();
    //    JsonFactory factory = objectMapper.getFactory();
    //    final int[] escapesArray = CharacterEscapes.standardAsciiEscapesForJSON();
    //    escapesArray['/'] = CharacterEscapes.ESCAPE_STANDARD;
    //    CharacterEscapes escapes = new CharacterEscapes() {
    //      @Override
    //      public int[] getEscapeCodesForAscii() {
    //        return escapesArray;
    //      }
    //
    //      @Override
    //      public SerializableString getEscapeSequence(int i) {
    //        return null;
    //      }
    //    };
    //    factory.setCharacterEscapes(escapes);
  }

  public static final JsonOperator getInstance() {
    return InnerHolder.INSTANCE;
  }

  private final ObjectMapper objectMapper;

  public <T> T fromJson(String jsonValue, Class<T> clz) throws IOException {
    return objectMapper.readValue(jsonValue, clz);
  }

  public <T> T fromJson(File f, Class<T> clz) throws IOException {
    return objectMapper.readValue(f, clz);
  }

  public <T> T fromJson(File f, TypeReference<T> ref) throws IOException {
    return objectMapper.readValue(f, ref);
  }

  public String toJson(Object obj) throws JsonProcessingException {
    return objectMapper.writeValueAsString(obj);
  }

}
